package com.message.Volcengine_ai_API.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.message.Baidu_ai_API.util.FileSetUtil;
import com.message.Baidu_ai_API.util.FileUtil;
import com.message.Volcengine_ai_API.VolcengineConfig.VolcengineExConfig;
import com.message.Volcengine_ai_API.service.VolcenginePictureService;
import com.message.Volcengine_ai_API.utils.Base64Util;
import com.message.Volcengine_ai_API.utils.VolcengineUtil;
import com.message.Volcengine_ai_API.vo.VolAgeChangeVo;
import com.message.Volcengine_ai_API.vo.VolEmotionPortraitVo;
import com.message.Volcengine_ai_API.vo.VolHairStyleVo;
import com.message.Volcengine_ai_API.vo.VolThreeDGameCartoonVo;
import com.volcengine.service.visual.IVisualService;
import com.volcengine.service.visual.impl.VisualServiceImpl;
import com.volcengine.service.visual.model.request.VisualJPCartoonRequest;
import com.volcengine.service.visual.model.response.VisualJPCartoonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.*;
import java.util.*;

@Service
public class VolcenginePictureServiceImpl implements VolcenginePictureService {

    @Autowired
    private VolcengineExConfig volcengineExConfig;
    @Value("${external.resource.dir}")
    private String externalResourceDir;
    private final RestTemplate restTemplate;//发http的
    @Value("${service.api_service.api_key}")
    private String API_KEY; //API密钥
    public VolcenginePictureServiceImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    @Override
    public List<String> TextToImage(String text, Boolean add_logo, Integer schedule_conf, Integer position, String logo_text_content) throws Exception {

        String AccessKeyID = "AKLTOWYxNmFkMmE3NDBhNDU4Mjg3YTEzYzRhMWMzY2I4ODI";// apikey
        String SecretAccessKey = "T1Rjd016Z3haRGM0TlRJeE5EUTBObUU0TVRNNVpUUmxPVGRpT1dKbU56Yw=="; //密钥
        String endpoint = "visual.volcengineapi.com";//访问地址
        String path = "/"; //访问路径url
        String service = "cv";//服务，默认cv
        String region = "cn-north-1";//服务地址
        String schema = "https";//默认https
        String action = "CVProcess";
        String version = "2022-08-31";
        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);
        JSONObject req=new JSONObject();
        req.put("req_key", "high_aes_general_v20_L");
        req.put("prompt", text);
        req.put("req_schedule_conf", "general_v20_9B_pe");//标准版：general_v20_9B_rephraser 美感版：general_v20_9B_pe
        req.put ("model_version", "general_v2.0_L");
        req.put ("return_url", false);
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        List<String> list=volcengineUtil.doRequest("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);
        Base64Util.Base64ToImage(list,externalResourceDir);
        return list;
    }

    @Override
    public List<String> JPCartoon(MultipartFile image, String cartoon_type) throws Exception {
        String fileName= FileSetUtil.resetFileName(114514,externalResourceDir,image);//生成的filename无后缀
        File file=FileSetUtil.saveFile(image,externalResourceDir,fileName);//生成的file为png文件
   String image_url= Base64Util.imageToBase64(file);
        String AccessKeyID = "AKLTOWYxNmFkMmE3NDBhNDU4Mjg3YTEzYzRhMWMzY2I4ODI";// apikey
        String SecretAccessKey = "T1Rjd016Z3haRGM0TlRJeE5EUTBObUU0TVRNNVpUUmxPVGRpT1dKbU56Yw=="; //密钥
        IVisualService visualService = VisualServiceImpl.getInstance();
        visualService.setAccessKey(AccessKeyID);
        visualService.setSecretKey(SecretAccessKey);
        VisualJPCartoonRequest req = new VisualJPCartoonRequest();
        req.setImageBase64(image_url);
        req.setCartoonType(cartoon_type);
        req.setRotation(1);
        try {
            VisualJPCartoonResponse resp = visualService.jpCartoon(req);

            // 提取 image 属性
            if (resp != null && resp.getData() != null) {
                String imageBase64 = resp.getData().getImage();
                Base64Util.Base64ToImage(Arrays.asList(imageBase64),externalResourceDir);
                return Arrays.asList(imageBase64);
            } else {
                throw new RuntimeException("Response data is null");
            }
     }
        catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to process image", e);
        }
    }

    @Override
    public List<String> SinglePhoto(String req_key, String binary_data_base64) throws Exception {
        String AccessKeyID = "AKLTOWYxNmFkMmE3NDBhNDU4Mjg3YTEzYzRhMWMzY2I4ODI";// apikey
        String SecretAccessKey = "T1Rjd016Z3haRGM0TlRJeE5EUTBObUU0TVRNNVpUUmxPVGRpT1dKbU56Yw=="; //密钥
        String endpoint = "visual.volcengineapi.com";//访问地址
        String path = "/"; //访问路径url
        String service = "cv";//服务，默认cv
        String region = "cn-north-1";//服务地址
        String schema = "https";//默认https
        String action = "HighAesSmartDrawing";
        String version = "2022-08-31";
        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);
        JSONObject req=new JSONObject();
        req.put("req_key", req_key);
        req.put("binary_data_base64",Arrays.asList(binary_data_base64));
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        List<String> list=volcengineUtil.doRequest("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);

        Base64Util.Base64ToImage(list,externalResourceDir);
        return list;
    }

    @Override
    public List<String> SmudgeEditing(String[] binary_data_base64, String custom_prompt) throws Exception {
        String AccessKeyID = "AKLTOWYxNmFkMmE3NDBhNDU4Mjg3YTEzYzRhMWMzY2I4ODI";// apikey
        String SecretAccessKey = "T1Rjd016Z3haRGM0TlRJeE5EUTBObUU0TVRNNVpUUmxPVGRpT1dKbU56Yw=="; //密钥
        String endpoint = "visual.volcengineapi.com";//访问地址
        String path = "/"; //访问路径url
        String service = "cv";//服务，默认cv
        String region = "cn-north-1";//服务地址
        String schema = "https";//默认https
        String action = "Img2ImgInpaintingEdit";
        String version = "2022-08-31";
        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);
        JSONObject req=new JSONObject();
        req.put("req_key", "i2i_inpainting_edit");
        req.put("binary_data_base64",Arrays.asList(binary_data_base64));
        req.put("custom_prompt",custom_prompt);
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        List<String> list=volcengineUtil.doRequest("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);
        Base64Util.Base64ToImage(list,externalResourceDir);
        return list;
    }
    @Override
    public List<String> SmearElimination(String[] binary_data_base64) throws Exception {
        String AccessKeyID = "AKLTOWYxNmFkMmE3NDBhNDU4Mjg3YTEzYzRhMWMzY2I4ODI";// apikey
        String SecretAccessKey = "T1Rjd016Z3haRGM0TlRJeE5EUTBObUU0TVRNNVpUUmxPVGRpT1dKbU56Yw=="; //密钥
        String endpoint = "visual.volcengineapi.com";//访问地址
        String path = "/"; //访问路径url
        String service = "cv";//服务，默认cv
        String region = "cn-north-1";//服务地址
        String schema = "https";//默认https
        String action = "Img2ImgInpainting";
        String version = "2022-08-31";
        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);
        JSONObject req=new JSONObject();
        req.put("req_key", "i2i_inpainting");
        req.put("binary_data_base64",Arrays.asList(binary_data_base64));
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        List<String> list=volcengineUtil.doRequest("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);
        Base64Util.Base64ToImage(list,externalResourceDir);
        return list;
    }
    @Override
    public List<String> PortraitMatting(String image_base64) throws Exception {
        String AccessKeyID = "AKLTOWYxNmFkMmE3NDBhNDU4Mjg3YTEzYzRhMWMzY2I4ODI";// apikey
        String SecretAccessKey = "T1Rjd016Z3haRGM0TlRJeE5EUTBObUU0TVRNNVpUUmxPVGRpT1dKbU56Yw=="; //密钥
        String endpoint = "visual.volcengineapi.com";//访问地址
        String path = "/"; //访问路径url
        String service = "cv";//服务，默认cv
        String region = "cn-north-1";//服务地址
        String schema = "https";//默认https
        String action = "HumanSegment";
        String version = "2020-08-26";
        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);
        JSONObject req=new JSONObject();
        req.put("image_base64", image_base64);
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        List<String> list=volcengineUtil.doRequest("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);

        Base64Util.Base64ToImage(list,externalResourceDir);
        return list;
    }

    @Override
    public Map<String, Object> emotionPortrait(VolEmotionPortraitVo volEmotionPortraitVo) throws Exception {

        String AccessKeyID = "AKLTNWMzZWJlYWRhYWQ1NDBkYWEyOTlhMzJlMDRhMWJhNWQ";// apikey
        String SecretAccessKey = "T1dRMU0yWmtNREUyTm1KaU5ERmhNemxtWkRZeVpUa3pPV0l3TURjNU4yWQ=="; //密钥
        String endpoint = "visual.volcengineapi.com";//访问地址
        String path = "/"; //访问路径url
        String service = "cv";//服务，默认cv
        String region = "cn-north-1";//服务地址
        String schema = "https";//默认https
        String action = "CVProcess";
        String version = "2022-08-31";
        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);

        System.out.println("Converted Date: " + date);
        HashMap<String, String> queryMap = new HashMap<>();
        JSONObject req=new JSONObject();
        req.put("req_key", "emotion_portrait");
        req.put("binary_data_base64",Arrays.asList(volEmotionPortraitVo.getBinary_data_base64()));
        req.put("target_emotion", volEmotionPortraitVo.getTarget_emotion());
        System.out.println(req);
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        return  volcengineUtil.doRequestInMap("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);
    }

    @Override
    public Map<String, Object> hairStyle(VolHairStyleVo volHairStyleVo) throws Exception{
        String AccessKeyID = "AKLTNWMzZWJlYWRhYWQ1NDBkYWEyOTlhMzJlMDRhMWJhNWQ";// apikey
        String SecretAccessKey = "T1dRMU0yWmtNREUyTm1KaU5ERmhNemxtWkRZeVpUa3pPV0l3TURjNU4yWQ=="; //密钥
        String endpoint = "visual.volcengineapi.com";//访问地址
        String path = "/"; //访问路径url
        String service = "cv";//服务，默认cv
        String region = "cn-north-1";//服务地址
        String schema = "https";//默认https
        String action = "CVProcess";
        String version = "2022-08-31";
        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);

        System.out.println("Converted Date: " + date);
        JSONObject req=new JSONObject();
        req.put("req_key", "hair_style");
        req.put("binary_data_base64",Arrays.asList(volHairStyleVo.getBinary_data_base64()));
        req.put("hair_type", volHairStyleVo.getHair_type());
        System.out.println(req);
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        return  volcengineUtil.doRequestInMap("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);
    }

    @Override
    public Map ageChange(VolAgeChangeVo volAgeChangeVo) throws Exception {
        String AccessKeyID = volcengineExConfig.getAccessKeyID();// apikey
        String SecretAccessKey = volcengineExConfig.getSecretAccessKey(); //密钥
        String endpoint = volcengineExConfig.getEndpoint();//访问地址
        String path = volcengineExConfig.getPath(); //访问路径url
        String service = volcengineExConfig.getService();//服务，默认cv
        String region = volcengineExConfig.getRegion();//服务地址
        String schema = volcengineExConfig.getSchema();//默认https
        String action = "AllAgeGeneration";
        String version = "2022-08-31";

        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);

        System.out.println("Converted Date: " + date);
        JSONObject req=new JSONObject();
        req.put("req_key", "all_age_generation");
        req.put("binary_data_base64",Arrays.asList(volAgeChangeVo.getBinary_data_base64()));
        req.put("target_age", volAgeChangeVo.getTarget_age());
        req.put("do_risk", false);
        System.out.println(req);
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        return  volcengineUtil.doRequestInMap("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);
    }

    @Override
    public Map threeDGameCartoon(VolThreeDGameCartoonVo volThreeDGameCartoonVo) throws Exception {
        String AccessKeyID = volcengineExConfig.getAccessKeyID();// apikey
        String SecretAccessKey = volcengineExConfig.getSecretAccessKey(); //密钥
        String endpoint = volcengineExConfig.getEndpoint();//访问地址
        String path = volcengineExConfig.getPath(); //访问路径url
        String service = volcengineExConfig.getService();//服务，默认cv
        String region = volcengineExConfig.getRegion();//服务地址
        String schema = volcengineExConfig.getSchema();//默认https
        String action = "3DGameCartoon";
        String version = "2020-08-26";

        // 假设你已经有了一个 LocalTime 对象
        LocalTime localTime = LocalTime.now();

        // 使用当前日期和给定的时间创建 LocalDateTime
        LocalDateTime localDateTime = LocalDate.now().atTime(localTime);

        // 将 LocalDateTime 转换为 Instant
        Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();

        // 将 Instant 转换为 java.util.Date
        Date date = Date.from(instant);

        System.out.println("Converted Date: " + date);
        JSONObject req=new JSONObject();
//        req.put("image_base64",volThreeDGameCartoonVo.getImage_base64());
        req.put("image_url",volThreeDGameCartoonVo.getImage_url());
        System.out.println(req);
        VolcengineUtil volcengineUtil=new VolcengineUtil(region, service, schema, endpoint, path, AccessKeyID, SecretAccessKey);
        return  volcengineUtil.doRequestInMap("POST", new HashMap(), req.toJSONString().getBytes(), date, action, version);
    }

}
